ホームに戻る
出典 :
FrameworkElement.Parent プロパティ (System.Windows) | Microsoft Learn 【C#/WPF】ユーザーコントロールの親ウィンドウを調べる - tinyjoker.net LogicalTreeHelper.GetChildren メソッド (System.Windows) | Microsoft Docs WPF Windowに配置されたコントロールを列挙する - Qiita
目次 :

コントロールの親コントロールを取得する

Parent プロパティを参照する。

コントロールの親ウィンドウを取得する

System.Windows.Window.GetWindow() メソッドにより、そのコントロールの親ウィンドウを取得することができる。

コード例

using System.Windows; class MyControl : UserControl { : // 親ウィンドウの取得 // ユーザコントロール(自身)を渡す var parent = Window.GetWindow(this); : }

子コントロールの一覧を取得する

System.Windows.LogicalTreeHelper.GetChildren() メソッドにより、引数に指定されたコントロールの直接の子要素を取得することができる。
再帰的に呼び出すことで、含まれる子孫要素を全て取得することができる。

コード例

using System.Windows; // 異常一覧ウィンドウ public partial class NotifyWindow : Window { : // ボタン「○○」押下時の処理 (イベントハンドラ) private void ClearNotifies( object sender, RoutedEventArgs e ) { // 表示を再帰的に更新 Refresh( this ); } : // 表示を再帰的に更新 private void Refresh( DependencyObject obj ) { // obj が NotifyItem_Alert の場合 if( obj is NotifyItem_Alert ) { // 表示を更新して抜ける ( (NotifyItem_Alert)obj ).Update(); return; } // obj が NotifyItem_Warning の場合 else if( obj is NotifyItem_Warning ) { // 表示を更新して抜ける ( (NotifyItem_Warning)obj ).Update(); return; } // 子要素をスキャン // System.Windows.LogicalTreeHelper.GetChildren() foreach( var child in LogicalTreeHelper.GetChildren(obj)) { // 子要素が DependencyObject の場合、再帰的に子孫を辿る if( child is DependencyObject ) { Refresh( (DependencyObject)child ); } } } }
コントロールは全て DependencyObject を継承しているため、System.Windows.LogicalTreeHelper.GetChildren() の引数に指定することができる。
GetChildren() の戻り値はインタフェース IEnumerable であり、foreach で走査が可能である。